﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;



namespace msBsc.AppLogic.Cfg
{

    internal class LinqList<T> : IEnumerable<T>, IEnumerable
    {
        IEnumerable items;
        internal LinqList(IEnumerable items)
        {
            this.items = items;
        }
        IEnumerator<T> IEnumerable<T>.GetEnumerator()
        {
            foreach (T item in items)
                yield return item;
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            IEnumerable<T> ie = this;
            return ie.GetEnumerator();
        }
    }

    //public class PersonDataRowComparer : IEqualityComparer<DataRow>
    //{
    //    #region IEqualityComparer<DataRow> Members

    //    public bool Equals(DataRow x, DataRow y)
    //    {
    //        return (x.Field<int>(dicField) == y.Field<int>(dicField));
    //    }

    //    public int GetHashCode(DataRow obj)
    //    {
    //        return obj.ToString().GetHashCode();
    //    }
    //    public string dicField
    //    {
    //        get;
    //        set;
    //    }

    //    #endregion
    //}

    public class CustTable
    {
        public DataTable dtCustTable
        {
            set;
            get;
        }
        public CustTable(string strTableNme, string strColS)
        {
            dtCustTable = new DataTable();
            string[] arrtem1 = strColS.Split(new char[] { ',' });
            for (int i = 0; i < arrtem1.Length; i++)
            {
                if (arrtem1[i] != string.Empty)
                {
                    dtCustTable.Columns.Add(arrtem1[i]);
                }
            }
            dtCustTable.TableName = strTableNme;
        }
        public void AddRow(params object[] args)
        {
            DataRow drtem = dtCustTable.NewRow();
            for (int i = 0; i < args.Length; i++)
            {
                string field = (string)args[i];
                drtem[i] = field;
            }
            dtCustTable.Rows.Add(drtem);
            dtCustTable.AcceptChanges();
        }
        public string GetJson()
        {
            if (dtCustTable == null || dtCustTable.Rows.Count <= 0)
                return "";
            return HttpTools.GetJsonByTable(dtCustTable, "", 100, "");
        }
    }

    public class HttpTools
    {
        public HttpTools()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static string EzUrlEncode(string str)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            byte[] data = UrlEncodeBytesToBytesInternal(bytes, 0, bytes.Length, false);
            return Encoding.ASCII.GetString(data);

        }
        internal static bool IsSafe(char ch)
        {
            if ((((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z'))) || ((ch >= '0') && (ch <= '9')))
            {
                return true;
            }
            switch (ch)
            {
                case '!':
                case '@':
                case '$':
                case '&':
                case '*':
                case '(':
                case ')':
                case '=':
                case ':':
                case '/':
                case ';':
                case '?':
                case '+':
                case '\'':
                case ',':
                case '#':
                    return true;
            }
            return false;
        }

        internal static char IntToHex(int n)
        {
            if (n <= 9)
            {
                return (char)(n + 0x30);
            }
            return (char)((n - 10) + 0x61);
        }
        private static byte[] UrlEncodeBytesToBytesInternal(byte[] bytes, int offset, int count, bool alwaysCreateReturnValue)
        {
            int num = 0;
            int num2 = 0;
            for (int i = 0; i < count; i++)
            {
                char ch = (char)bytes[offset + i];
                if (ch == ' ')
                {
                    num++;
                }
                else if (!IsSafe(ch))
                {
                    num2++;
                }
            }
            if ((!alwaysCreateReturnValue && (num == 0)) && (num2 == 0))
            {
                return bytes;
            }
            byte[] buffer = new byte[count + (num2 * 2)];
            int num4 = 0;
            for (int j = 0; j < count; j++)
            {
                byte num6 = bytes[offset + j];
                char ch2 = (char)num6;
                if (IsSafe(ch2))
                {
                    buffer[num4++] = num6;
                }
                else if (ch2 == ' ')
                {
                    buffer[num4++] = 0x20;
                }

                else
                {
                    buffer[num4++] = 0x25;
                    buffer[num4++] = (byte)IntToHex((num6 >> 4) & 15);
                    buffer[num4++] = (byte)IntToHex(num6 & 15);
                }
            }
            return buffer;
        }



        public static msBsc.AppLogic.Cfg.SynDictionary GetRowHash(string strXml, DataColumnCollection Columns)
        {
            msBsc.AppLogic.Cfg.SynDictionary RowHash = new msBsc.AppLogic.Cfg.SynDictionary(false);
            System.Xml.XmlDocument dsxxx = new System.Xml.XmlDocument();
            dsxxx.LoadXml(strXml);
            HttpTools.GetRowHashtem(RowHash, dsxxx.ChildNodes[0], null);
            return RowHash;
        }
        public static msBsc.AppLogic.Cfg.SynDictionary GetRowHash(System.Xml.XmlDocument xDoc, DataColumnCollection Columns)
        {
            msBsc.AppLogic.Cfg.SynDictionary RowHash = new msBsc.AppLogic.Cfg.SynDictionary(false);

            System.Xml.XmlNode root = xDoc.DocumentElement.ChildNodes[0];
            while (root.ChildNodes.Count > 0)
            {
                if (root.NodeType == System.Xml.XmlNodeType.CDATA)
                    break;
                root = root.ChildNodes[0];
            }
            if (root.NodeType == System.Xml.XmlNodeType.CDATA)
            {
                System.Xml.XmlCDataSection xds = (System.Xml.XmlCDataSection)root;
                System.Xml.XmlDocument dsxxx = new System.Xml.XmlDocument();
                dsxxx.LoadXml(xds.Data);
                HttpTools.GetRowHashtem(RowHash, dsxxx.ChildNodes[0], Columns);
            }
            return RowHash;
        }

        public static void GetRowHashtem(msBsc.AppLogic.Cfg.SynDictionary RowHash, System.Xml.XmlNode xnp, DataColumnCollection Columns)
        {
            //System.Xml.XmlElement xep = (System.Xml.XmlElement)xnp; // 将子节点类型转换为XmlElement类型
            //if (xnp.Attributes != null && xnp.LocalName == "row")
            //{
            //    RowHash["RATE_ITEM_ID"] = xnp.Attributes.GetNamedItem("keyValue").InnerText;
            //}
            if (xnp.Attributes != null && xnp.LocalName == "cell")
            {
                if (xnp.Attributes.GetNamedItem("colName").InnerText == string.Empty)
                {
                    return;
                }
                else if (Columns == null)
                {
                    string strColumnNme = xnp.Attributes.GetNamedItem("colName").InnerText;
                    if (xnp.SelectNodes("value").Count > 0)
                        RowHash[strColumnNme] = xnp.SelectNodes("value")[0].InnerText;
                    return;
                }
                else if (Columns.IndexOf(xnp.Attributes.GetNamedItem("colName").InnerText) != -1)
                {
                    string strColumnNme = xnp.Attributes.GetNamedItem("colName").InnerText;
                    //if (Columns == null)
                    //{
                    //    if (xnp.SelectNodes("value").Count > 0)
                    //        RowHash[strColumnNme] = xnp.SelectNodes("value")[0].InnerText;
                    //    return;
                    //}

                    if (Columns[strColumnNme].DataType == typeof(string))
                    {
                        if (xnp.SelectNodes("value").Count > 0)
                            RowHash[strColumnNme] = xnp.SelectNodes("value")[0].InnerText;
                        else if (!Columns[strColumnNme].AllowDBNull)
                            RowHash[strColumnNme] = "tem";
                    }
                    if (Columns[strColumnNme].DataType == typeof(global::System.DateTime))
                    {
                        if (xnp.SelectNodes("value").Count > 0)
                        {
                            if (string.IsNullOrEmpty(xnp.SelectNodes("value")[0].InnerText))
                                RowHash[strColumnNme] = DBNull.Value;
                            else
                                RowHash[strColumnNme] = DateTime.Parse(xnp.SelectNodes("value")[0].InnerText);
                        }
                    }
                    if (Columns[strColumnNme].DataType == typeof(global::System.TimeSpan))
                    {
                        if (xnp.SelectNodes("value").Count > 0)
                        {
                            if (string.IsNullOrEmpty(xnp.SelectNodes("value")[0].InnerText))
                                RowHash[strColumnNme] = DBNull.Value;
                            else
                                RowHash[strColumnNme] = TimeSpan.Parse(xnp.SelectNodes("value")[0].InnerText);
                        }
                    }
                    if (Columns[strColumnNme].DataType == typeof(decimal))
                    {
                        if (xnp.SelectNodes("value").Count > 0)
                        {
                            if (string.IsNullOrEmpty(xnp.SelectNodes("value")[0].InnerText))
                                RowHash[strColumnNme] = 0;
                            else
                                RowHash[strColumnNme] = decimal.Parse(xnp.SelectNodes("value")[0].InnerText);
                        }
                    }
                    if (Columns[strColumnNme].DataType == typeof(int))
                    {
                        if (xnp.SelectNodes("value").Count > 0)
                        {
                            if (string.IsNullOrEmpty(xnp.SelectNodes("value")[0].InnerText))
                                RowHash[strColumnNme] = 0;
                            else
                                RowHash[strColumnNme] = int.Parse(xnp.SelectNodes("value")[0].InnerText);
                        }
                    }
                    if (Columns[strColumnNme].DataType == typeof(bool))
                    {
                        if (xnp.SelectNodes("value").Count > 0)
                            RowHash[strColumnNme] = xnp.SelectNodes("value")[0].InnerText == "True" || xnp.SelectNodes("value")[0].InnerText == "true";
                    }
                    return;
                }
            }
            if (!xnp.HasChildNodes)
                return;
            System.Xml.XmlNodeList nodeList = xnp.ChildNodes; // 获取root根节点所有子节点 
            foreach (System.Xml.XmlNode xn in nodeList)
            {
                HttpTools.GetRowHashtem(RowHash, xn, Columns);
            }
        }


        public static string EncoderXmlString(DataTable dt)
        {
            string ReturnXml = "";
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                ReturnXml += "<data>";
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    ReturnXml += "<" + dt.Columns[i].ColumnName + "><![CDATA[" + dt.Rows[r][dt.Columns[i].ColumnName].ToString() + "]]></" + dt.Columns[i].ColumnName + ">";
                }
                ReturnXml += "</data>";
            }
            ReturnXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + ReturnXml + "";
            return ReturnXml;
        }

        public static string EncoderXmlString(DataRow drw)
        {
            string ReturnXml = "";
            for (int i = 0; i < drw.Table.Columns.Count; i++)
            {
                ReturnXml += "<" + drw.Table.Columns[i].ColumnName + "><![CDATA[" + drw[drw.Table.Columns[i].ColumnName].ToString() + "]]></" + drw.Table.Columns[i].ColumnName + ">";
                //ReturnXml += "" + drw.Table.Columns[i].ColumnName + "='" + drw[drw.Table.Columns[i].ColumnName].ToString() + "' ";
            }
            //ReturnXml += " /></selection>";
            ReturnXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><data>" + ReturnXml + " </data>";
            return ReturnXml;
        }
        public static string EncoderXmlString(msBsc.AppLogic.Cfg.SynDictionary RowHash)
        {
            string ReturnXml = "";
            string[] arrKey = RowHash.Keys;// new string[RowHash.Keys.Count];
            //RowHash.Keys.CopyTo(arrKey, 0);
            for (int i = 0; i < arrKey.Length; i++)
            {
                ReturnXml += "<" + arrKey[i] + "><![CDATA[" + RowHash[arrKey[i]].ToString() + "]]></" + arrKey[i] + ">";
                //drNew[arrKey[i]] = RowHash[arrKey[i]];
                //drNewCargo[arrKey[i]] = RowHash[arrKey[i]];
            }
            //for (int i = 0; i < htTem.Count; i++)
            //{
            //    ReturnXml += "<" + drw.Table.Columns[i].ColumnName + "><![CDATA[" + drw[drw.Table.Columns[i].ColumnName].ToString() + "]]></" + drw.Table.Columns[i].ColumnName + ">";
            //    //ReturnXml += "" + drw.Table.Columns[i].ColumnName + "='" + drw[drw.Table.Columns[i].ColumnName].ToString() + "' ";
            //}
            //ReturnXml += " /></selection>";
            ReturnXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><data>" + ReturnXml + " </data>";
            return ReturnXml;
        }

        public static void SetDataValueByHashtableValue(msBsc.AppLogic.Cfg.SynDictionary RowHash, DataRow drw)
        {
            SetDataValueByHashtableValue(RowHash, drw, "", "");
        }

        public static void SetDataValueByHashtableValue(msBsc.AppLogic.Cfg.SynDictionary RowHash, DataRow drw, string NotSetFieldS)
        {
            SetDataValueByHashtableValue(RowHash, drw, NotSetFieldS, "");
        }


        public static void SetDataValueByHashtableValue(msBsc.AppLogic.Cfg.SynDictionary RowHash, DataRow drw, string NotSetFieldS, string OnlySetFieldS)
        {
            if (NotSetFieldS != string.Empty)
            {
                NotSetFieldS = "," + NotSetFieldS + ",";
            }
            if (OnlySetFieldS != string.Empty)
            {
                OnlySetFieldS = "," + OnlySetFieldS + ",";
            }
            //string[] arrKey = new string[RowHash.Keys.Count];
            //RowHash.Keys.CopyTo(arrKey, 0);
            foreach (string strColum in RowHash.Keys)
            {
                //string strColum = arrKey[i];
                if (strColum == string.Empty || drw.Table.Columns.IndexOf(strColum) == -1
                    || NotSetFieldS != string.Empty && NotSetFieldS.IndexOf("," + strColum + ",") != -1
                    || OnlySetFieldS != string.Empty && OnlySetFieldS.IndexOf("," + strColum + ",") == -1)
                {
                    continue;
                }
                string strValue = RowHash[strColum].ToString();
                if (drw[strColum].ToString() == strValue)
                {
                    continue;
                }
                if (drw.Table.Columns[strColum].DataType == typeof(global::System.DateTime))
                {
                    if (string.IsNullOrEmpty(strValue))
                    {
                        SetRowCelValue(drw, strColum, DBNull.Value);
                        //drw[strColum] = DBNull.Value;
                    }
                    else
                    {
                        SetRowCelValue(drw, strColum, DateTime.Parse(strValue));
                        //drw[strColum] = DateTime.Parse(strValue);
                    }
                }
                else if (drw.Table.Columns[strColum].DataType == typeof(global::System.TimeSpan))
                {
                    if (string.IsNullOrEmpty(strValue))
                    {
                        SetRowCelValue(drw, strColum, DBNull.Value);
                        //drw[strColum] = DBNull.Value;
                    }
                    else
                    {
                        SetRowCelValue(drw, strColum, TimeSpan.Parse(strValue));
                        //drw[strColum] = TimeSpan.Parse(strValue);
                    }
                }
                else if (drw.Table.Columns[strColum].DataType == typeof(decimal))
                {
                    if (string.IsNullOrEmpty(strValue))
                    {
                        SetRowCelValue(drw, strColum, 0);
                        //drw[strColum] = 0;
                    }
                    else
                    {
                        SetRowCelValue(drw, strColum, decimal.Parse(strValue));
                        //drw[strColum] = decimal.Parse(strValue);
                    }
                }
                else if (drw.Table.Columns[strColum].DataType == typeof(int))
                {
                    if (string.IsNullOrEmpty(strValue))
                    {
                        SetRowCelValue(drw, strColum, 0);
                        //drw[strColum] = 0;
                    }
                    else if (strValue.IndexOf(".") != -1)
                    {
                        SetRowCelValue(drw, strColum, Convert.ToInt32(Convert.ToDecimal(strValue)));
                        //drw[strColum] = Convert.ToInt32(Convert.ToDecimal(strValue));
                    }
                    else
                    {
                        SetRowCelValue(drw, strColum, int.Parse(strValue));
                        //drw[strColum] = int.Parse(strValue);
                    }
                }
                else if (drw.Table.Columns[strColum].DataType == typeof(Int16))
                {
                    if (string.IsNullOrEmpty(strValue.Trim()))
                    {
                        SetRowCelValue(drw, strColum, 0);
                        //drw[strColum] = 0;
                    }
                    else if (strValue.IndexOf(".") != -1)
                    {
                        SetRowCelValue(drw, strColum, Convert.ToInt16(Convert.ToDecimal(strValue)));
                        //drw[strColum] = Convert.ToInt16(Convert.ToDecimal(strValue));
                    }
                    else
                    {
                        SetRowCelValue(drw, strColum, Int16.Parse(strValue.Trim()));
                        //drw[strColum] = Int16.Parse(strValue.Trim());
                    }
                }
                else if (drw.Table.Columns[strColum].DataType == typeof(bool))
                {
                    SetRowCelValue(drw, strColum, strValue.ToLower() == "true" || strValue.ToLower() == "1");
                    //drw[strColum] = strValue.ToLower() == "true" || strValue.ToLower() == "1";
                }
                else
                {
                    SetRowCelValue(drw, strColum, strValue);
                    //drw[strColum] = strValue;
                }
            }


        }
        public static void SetRowCelValue(DataRow drw, string strColum, object _objValue)
        {
            object _objRowCel = drw[strColum];
            if (_objRowCel != _objValue)
            {
                string strtem1111 = "", strtem2222 = "";
                if (_objRowCel != null && _objRowCel != DBNull.Value)
                {
                    strtem1111 = _objRowCel.ToString();
                }
                if (_objValue != null && _objValue != DBNull.Value)
                {
                    strtem2222 = _objValue.ToString();
                }
                if (drw.Table.Columns[strColum].DataType == typeof(decimal) || drw.Table.Columns[strColum].DataType == typeof(int) || drw.Table.Columns[strColum].DataType == typeof(Int16))
                {
                    if (strtem1111 != strtem2222 && strtem1111 != string.Empty && strtem2222 != string.Empty)
                    {
                        if (decimal.Parse(strtem1111) == decimal.Parse(strtem2222))
                        {
                            return;
                        }
                    }
                }



                if (strtem1111 != strtem2222)
                {
                    drw[strColum] = _objValue;
                }
            }
        }
        public static msBsc.AppLogic.Cfg.SynDictionary GetHashtByValue(string strColNme, string strValue, msBsc.AppLogic.Cfg.SynDictionary htReturn)
        {
            if (htReturn == null)
            {
                htReturn = new msBsc.AppLogic.Cfg.SynDictionary(false);
            }
            if (htReturn.ContainsKey(strColNme))
            {
                htReturn[strColNme] = strValue;
            }
            else
            {
                htReturn.Add(strColNme, strValue);
            }
            return htReturn;
        }

        public static msBsc.AppLogic.Cfg.SynDictionary GetHashtByRow(DataRow drw, msBsc.AppLogic.Cfg.SynDictionary htReturn)
        {
            if (htReturn == null)
            {
                htReturn = new msBsc.AppLogic.Cfg.SynDictionary(false);
            }
            for (int i = 0; i < drw.Table.Columns.Count; i++)
            {
                string strColNme = drw.Table.Columns[i].ColumnName;
                if (htReturn.ContainsKey(strColNme))
                {
                    htReturn[strColNme] = drw[strColNme].ToString();
                }
                else
                {
                    htReturn.Add(strColNme, drw[strColNme].ToString());
                }
            }
            return htReturn;
        }
        public static string GetjsonStr(msBsc.AppLogic.Cfg.SynDictionary htPanel)
        {
            return GetjsonStr(htPanel, true);
        }
        /// <summary>
        /// 返回值不包含外层的"[{}]"
        /// </summary>
        /// <param name="htPanel"></param>
        /// <returns></returns>
        public static string GetjsonStr(msBsc.AppLogic.Cfg.SynDictionary htPanel, bool blEncodeValue)
        {
            string strTem = "";
            if (htPanel != null && htPanel.Count > 0)
            {
                string[] arrKey = htPanel.Keys;
                strTem = "";
                for (int i = 0; i < arrKey.Length; i++)
                {
                    if (i != 0)
                        strTem += ",";
                    if (blEncodeValue)
                        strTem += "\"" + arrKey[i] + "\":\"" + stringToJson(htPanel[arrKey[i]].ToString()) + "\"";
                    else
                        strTem += "\"" + arrKey[i] + "\":" + htPanel[arrKey[i]].ToString() + "";//值可能是类，可能是字符串
                }
            }
            return strTem;
        }
        /// <summary>
        /// 返回值不包含外层的"[{}]"
        /// </summary>
        /// <param name="strJScrip"></param>
        /// <param name="strAlertMsg"></param>
        /// <param name="strCustJson"></param>
        /// <param name="htPanel"></param>
        /// <param name="htData"></param>
        /// <returns></returns>
        public static string GetjsonStr(string strJScrip, string strAlertMsg, string strClosew, string strCustJson, msBsc.AppLogic.Cfg.SynDictionary htPanel, msBsc.AppLogic.Cfg.SynDictionary htData)
        {
            string strTem = "[{\"aaaa\":\"dfdfdfd\",\"aaada\":\"dfdfddfd\",\"row\":{\"d\":\"b\",\"c\":\"g\"},\"row1\":{\"d\":\"b\",\"c\":\"g\"}}]";
            StringBuilder strJson = new StringBuilder();
            strJson.Append("\"jscrip\":\"" + stringToJson(strJScrip) + "\"");
            strJson.Append(",\"jmsg\":\"" + stringToJson(strAlertMsg) + "\"");
            strJson.Append(",\"jsclose\":\"" + stringToJson(strClosew) + "\"");
            strJson.Append(",\"jcust\":{" + strCustJson + "}");


            if (htPanel != null && htPanel.Count > 0)
            {
                string[] arrKey = htPanel.Keys;
                //htPanel.Keys.CopyTo(arrKey, 0);
                strTem = "";
                for (int i = 0; i < arrKey.Length; i++)
                {
                    if (i != 0)
                        strTem += ",";
                    strTem += "\"" + arrKey[i] + "\":\"" + stringToJson(htPanel[arrKey[i]].ToString()) + "\"";
                }
                strJson.Append(",\"jpanel\":{" + strTem + "}");
            }
            if (htData != null && htData.Count > 0)
            {
                string[] arrKey = htData.Keys;
                //htData.Keys.CopyTo(arrKey, 0);
                StringBuilder strTemsp = new StringBuilder();
                for (int i = 0; i < arrKey.Length; i++)
                {
                    if (i != 0)
                        strTemsp.Append(",");
                    strTemsp.Append("\"" + arrKey[i] + "\":\"" + stringToJson(htData[arrKey[i]].ToString()) + "\"");
                }
                strJson.Append(",\"jrow\":{" + strTemsp.ToString() + "}");
            }
            //strJson = "[{" + strJson + "}]";
            return strJson.ToString();
        }

        public static string stringToJson(string s)
        {
            return s.Replace("\\", "\\\\")
                .Replace("\t", "\\t")
                .Replace("\r", "\\r")
                .Replace("\n", "\\n")
                .Replace("\f", "\\f")
                .Replace("\b", "\\b")
                .Replace("/", "\\/")
                .Replace("\'", "\\\'")
                .Replace("\"", "\\\"");
            //return  Microsoft.JScript.GlobalObject.encodeURIComponent(s);
            //StringBuilder sb = new StringBuilder();
            //for (int i = 0; i < s.Length; i++)
            //{
            //    char c = s[i];
            //    switch (c)
            //    {
            //        case '\"':
            //            sb.Append("\\\"");
            //            break;
            //        case '\'':
            //            sb.Append("\\\'");
            //            break;
            //        case '\\':
            //            sb.Append("\\\\");
            //            break;
            //        case '/':
            //            sb.Append("\\/");
            //            break;
            //        case '\b':
            //            sb.Append("\\b");
            //            break;
            //        case '\f':
            //            sb.Append("\\f");
            //            break;
            //        case '\n':
            //            sb.Append("\\n");
            //            break;
            //        case '\r':
            //            sb.Append("\\r");
            //            break;
            //        case '\t':
            //            sb.Append("\\t");
            //            break;
            //        default:
            //            sb.Append(c);
            //            break;
            //    }
            //}
            //return sb.ToString();
        }



        //针对jqgrid的数据处理

        /**
         * 
         * 
    $(function()
    {
            $("#gridTable").jqGrid({
                    url:'json/jqgrid.action',
                    datatype: "json",
                    height: 250,
                    colNames:['编号','用户名', '性别', '邮箱', 'QQ','手机号','出生日期'],
                    colModel:[
                            {name:'id',index:'id', sorttype:"int"},
                            {name:'userName',index:'userName',
                            {name:'gender',index:'gender',
                            {name:'email',index:'email', ;string"},
                            {name:'QQ',index:'QQ', ;            
                            {name:'mobilePhone',index:'mobilePhone', ;            
                            {name:'birthday',index:'birthday', sorttype:"date"}
                    ],
                    sortname:'id',
                    sortorder:'asc',
                    viewrecords:true,
                    rowNum:10,
                    rowList:[10,20,30],
                    jsonReader: {
                            root:"dataRows",                // 数据行（默认为：rows）
                            page: "curPage",            // 当前页
                            total: "totalPages",    // 总页数
                            records: "totalRecords",    // 总记录数
                            repeatitems : false                // 设置成false，在后台设置值的时候，可以乱序。且并非每个值都得设
                    },
                    prmNames:{rows:"page.pageSize",page:"page.curPageNo",sort:"page.orderBy",order:"page.order"},
                    pager:"#gridPager",
                    caption: "jqGrid与Struts2集成"
    }).navGrid('#gridPager',{edit:false,add:false,del:false});
    })
         * 
    * 该Struts2向客户端返回一个json对象。为了简便，数据不是从数据库获得的。
    * jqGrid默认期望返回的json对象格式要求如下：
    * {"page":"1","total":"2","records":"13",
    * "rows":[
    *                 {id:"1",cell:["1","polaris","男","polaris@gmail.com","772618379","18329382732","1985-10-2"]},
    *                 {id:"2",cell:["2","张三","女","zhangsan@163.com","272618382","15329382732","1986-10-12"]},
    *                 {id:"3",cell:["3","王五","女","wangwu@yahoo.com","172635372","13329389832","1987-12-21"]},
    *                 {id:"4",cell:["4","赵六","男","zhaoliu@sina.com","372618332","18929343731","1988-09-22"]}
    *         ]
    * }
    * 当然，在js中，可以通过jqGrid的jsonReader属性来修改默认格式
    * 因为默认的格式，rows的数据要求顺序不能变，且每个字段都得有值（空也得有"")。因而，
    * 在jsonReader中定义repeatitems : false。这样，rows就变成了：
    * "rows":[
    *                 {id:"1",userName:"polaris",gender:" 男",email:"polaris@gmail.com",QQ:"772618379",mobilePhone:"18329382732",birthday:"1985-10-2"]},
    *                 {id:"2",userName:"徐新华",gender:" 男",email:"xh.xu@163.com",QQ:"272618382",mobilePhone:"15329382732",birthday:"1986-10-12"]},
    *                 {id:"3",userName:"王五",gender:" 女",email:"wangwu@yahoo.com",QQ:"172635372",mobilePhone:"13329389832",birthday:"1987-12-21"]},
    *                 {id:"4",userName:"赵六",gender:" 女",email:"zhaoliu@sina.com",QQ:"372618332",mobilePhone:"18929343731",birthday:"1988-09-22"]}
    *         ]
    * @author xuxinhua
    *
    */

        /// <summary>
        /// 返回带{}的json字符串,针对jqgrid的数据处理
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="strKeyFieldNme"></param>
        /// <param name="strSortFieldNme"></param>
        /// <param name="iCurrPageNum"></param>
        /// <param name="iPageRows"></param>
        /// <param name="strSord"></param>
        /// <returns></returns>
        public static string GetJsonForJqgrid(DataTable dt, string strColNmeList, string strKeyFieldNme, string strSortFieldNme, int iCurrPageNum, int iPageRows, string strSord)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            //jsonBuilder.Append("\"");rows=10&page=2&sidx=&sord=asc   where (int)r[""] == 2
            jsonBuilder.Append("{\"page\":" + iCurrPageNum.ToString() + ",\"total\":" + System.Math.Ceiling(((double)(dt.Rows.Count) / (double)iPageRows)).ToString() + ",\"records\":" + dt.Rows.Count + ",\"rows\"");
            jsonBuilder.Append(":[");

            //只返回当前页数据
            if (strSortFieldNme != string.Empty && strSord != string.Empty && dt.Columns.IndexOf(strSortFieldNme) != -1)
                dt.DefaultView.Sort = strSortFieldNme + " " + strSord;
            LinqList<DataRowView> lqrows = new LinqList<DataRowView>(dt.DefaultView);
            IEnumerable<DataRowView> selectedRows = (from r in lqrows select r).Skip((iCurrPageNum - 1) * iPageRows).Take(iPageRows);
            int k = 0;
            string[] arrstrCol = strColNmeList.Split(new char[] { ',' });
            foreach (DataRowView row in selectedRows)
            {
                string strKey = row[0].ToString();
                if (strKeyFieldNme != string.Empty && dt.Columns.IndexOf(strKeyFieldNme) != -1)
                    strKey = row[strKeyFieldNme].ToString();
                if (k != 0)
                    jsonBuilder.Append(",");
                jsonBuilder.Append("{\"id\":\"" + strKey + "\",\"cell\":[");

                for (int j = 0; j < arrstrCol.Length; j++)
                {
                    if (arrstrCol[j] != string.Empty && dt.Columns.IndexOf(arrstrCol[j]) != -1)
                    {
                        jsonBuilder.Append("\"");
                        jsonBuilder.Append(HttpTools.stringToJson(row[arrstrCol[j]].ToString()));
                        jsonBuilder.Append("\",");
                    }
                }


                //for (int j = 0; j < dt.Columns.Count; j++)
                //{
                //    jsonBuilder.Append("\"");
                //    jsonBuilder.Append(HttpTools.stringToJson(row[dt.Columns[j].ColumnName].ToString()));
                //    jsonBuilder.Append("\",");
                //}
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("]}");
                k++;
            }
            //jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        public static string GetJsonByTable(DataTable dt, string strColNmeList, string strGroupField, int iCurrPageNum, int iPageRows, string strSordString,bool blGroupFull=true)
        {
            double ipageTotal = System.Math.Ceiling(((double)(dt.Rows.Count) / (double)iPageRows));
            if (iCurrPageNum > ipageTotal)
            {
                iCurrPageNum = (int)ipageTotal;
            }
            StringBuilder jsonBuilder = new StringBuilder();
            //jsonBuilder.Append("\"");rows=10&page=2&sidx=&sord=asc   where (int)r[""] == 2
            jsonBuilder.Append("{\"page\":" + iCurrPageNum.ToString() + ",\"total\":" + ipageTotal.ToString() + ",\"records\":" + dt.Rows.Count + ",\"rows\"");
            jsonBuilder.Append(":[");

            //只返回当前页数据
            string strViewSort = "";
            System.Collections.Generic.List<string> lsGroupFields = new List<string>();
            if (strGroupField != string.Empty)
            {
                strViewSort = strGroupField;
                string[] arrstrtem1 = strGroupField.Split(',');
                for (int i = 0; i < arrstrtem1.Length; i++)
                {
                    if (arrstrtem1[i].Trim() == string.Empty)
                    {
                        continue;
                    }
                    if (i == 0)
                    {
                        strGroupField = arrstrtem1[i].TrimStart().Split(' ')[0];
                    }
                    lsGroupFields.Add(arrstrtem1[i].TrimStart().Split(' ')[0]);
                }

            }
            if (strSordString != string.Empty)
            {
                //strViewSort += strViewSort == string.Empty ? strSordString : "," + strSordString;
                strViewSort = strSordString;
            }
            if (strViewSort!=string.Empty)
                dt.DefaultView.Sort = strViewSort;
            else
                dt.DefaultView.Sort="";
            int iCount=dt.DefaultView.Count;

            int iStart=0,iEnd=iCount-1;
            if(iCurrPageNum>0)
            {
                iStart = (iCurrPageNum - 1) * iPageRows;
                iEnd = iStart + iPageRows - 1;
            }
            if (iEnd >= iCount)
            {
                iEnd = iCount-1;
            }

            string[] arrstrCol = strColNmeList == string.Empty ? new string[] { } : strColNmeList.Split(new char[] { ',' });
            if (lsGroupFields.Count > 0 && strColNmeList==string.Empty)
            {
                System.Collections.Generic.List<string> lsColFields = new List<string>();
                int item333 = dt.Columns.Count;
                for (int j = 0; j < item333; j++)
                {
                    if (!lsGroupFields.Contains(dt.Columns[j].ColumnName))
                    {
                        lsColFields.Add(dt.Columns[j].ColumnName);
                    }
                }
                arrstrCol = lsColFields.ToArray();
            }
            StringBuilder sbRows = new StringBuilder();
            int iGroupRows = 0,iCRowCount=0;
            for (int i = iStart; i < iCount; i++)
            {
                if (strGroupField != string.Empty)
                {
                    //begin
                    if (i == iStart || i > 0 && dt.DefaultView[i][strGroupField].ToString() != dt.DefaultView[i - 1][strGroupField].ToString())
                    {
                        iCRowCount = 0;
                        sbRows.Clear();
                    }
                    else
                    {
                        sbRows.Append(",");
                    }

                    if (arrstrCol.Length > 0)
                    {
                        sbRows.Append("{");
                        int item222 = arrstrCol.Length;
                        for (int j = 0; j < item222; j++)
                        {
                            if (arrstrCol[j] != string.Empty)
                            {
                                sbRows.Append("\"");
                                sbRows.Append(arrstrCol[j]);
                                sbRows.Append("\":");
                                sbRows.Append("\"");
                                sbRows.Append(HttpTools.stringToJson(dt.DefaultView[i][arrstrCol[j]].ToString()));
                                if (j < item222 - 1)
                                {
                                    sbRows.Append("\",");
                                }
                                else
                                {
                                    sbRows.Append("\"");
                                }
                            }
                        }
                        sbRows.Append("}");
                    }
                    else
                    {
                        sbRows.Append("{");
                        int item222 = dt.Columns.Count;
                        for (int j = 0; j < item222; j++)
                        {
                            sbRows.Append("\"");
                            sbRows.Append(dt.Columns[j].ColumnName);
                            sbRows.Append("\":");
                            sbRows.Append("\"");
                            sbRows.Append(HttpTools.stringToJson(dt.DefaultView[i][dt.Columns[j].ColumnName].ToString()));
                            if (j < item222 - 1)
                            {
                                sbRows.Append("\",");
                            }
                            else
                            {
                                sbRows.Append("\"");
                            }
                        }
                        sbRows.Append("}");
                    }
                    iCRowCount++;

                    //保持分组完整
                    if (blGroupFull)
                    {
                        if (i == iEnd && i < iCount - 1 && dt.DefaultView[i][strGroupField].ToString() == dt.DefaultView[i + 1][strGroupField].ToString())
                        {
                            iEnd = iEnd + 1;
                        }
                    }

                    //end
                    if (i == iEnd || i < iCount - 1 && dt.DefaultView[i][strGroupField].ToString() != dt.DefaultView[i + 1][strGroupField].ToString())
                    {
                        if (iGroupRows > 0)
                        {
                            jsonBuilder.Append(",");
                        }
                        jsonBuilder.Append("{");
                        for (int k = 0; k < lsGroupFields.Count; k++)
                        {
                            if (k > 0)
                            {
                                jsonBuilder.Append(",");
                            }
                            jsonBuilder.Append("\"" + lsGroupFields[k] + "\":\"" + dt.DefaultView[i][lsGroupFields[k]].ToString() + "\"");
                        }
                        jsonBuilder.Append(",\"rCount\":\"" + iCRowCount.ToString() + "\",\"rows\":[" + sbRows.ToString() + "]}");
                        iGroupRows++;
                    }
                    if (i == iEnd)
                    {
                        break;
                    }
                }
                else
                {
                    sbRows.Clear();
                    if (arrstrCol.Length > 0)
                    {
                        sbRows.Append("{");
                        int item222 = arrstrCol.Length;
                        for (int j = 0; j < item222; j++)
                        {
                            if (arrstrCol[j] != string.Empty)
                            {
                                sbRows.Append("\"");
                                sbRows.Append(arrstrCol[j]);
                                sbRows.Append("\":");
                                sbRows.Append("\"");
                                sbRows.Append(HttpTools.stringToJson(dt.DefaultView[i][arrstrCol[j]].ToString()));
                                if (j < item222 - 1)
                                {
                                    sbRows.Append("\",");
                                }
                                else
                                {
                                    sbRows.Append("\"");
                                }
                            }
                        }
                        sbRows.Append("}");
                    }
                    else
                    {
                        sbRows.Append("{");
                        int item222 = dt.Columns.Count;
                        for (int j = 0; j < item222; j++)
                        {
                            sbRows.Append("\"");
                            sbRows.Append(dt.Columns[j].ColumnName);
                            sbRows.Append("\":");
                            sbRows.Append("\"");
                            sbRows.Append(HttpTools.stringToJson(dt.DefaultView[i][dt.Columns[j].ColumnName].ToString()));
                            if (j < item222 - 1)
                            {
                                sbRows.Append("\",");
                            }
                            else
                            {
                                sbRows.Append("\"");
                            }
                        }
                        sbRows.Append("}");
                    }

                    if (iGroupRows > 0)
                    {
                        jsonBuilder.Append(",");
                    }
                    //jsonBuilder.Append("{\"rCount\":\"" + iCRowCount.ToString() + "\",\"rows\":[" + sbRows.ToString() + "]}");
                    jsonBuilder.Append(sbRows.ToString());
                    iGroupRows++;

                    if (i == iEnd)
                    {
                        break;
                    }
                }
            }

            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
             
            return  jsonBuilder.ToString();
        }

        /// <summary>
        /// 返回带{}的json字符串,针对普通表的数据处理
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="strSortFieldNme"></param>
        /// <param name="iRCount"></param>
        /// <param name="strSord"></param>
        /// <returns></returns>
        public static string GetJsonByTable(DataTable dt, string strSortFieldNme, int iRCount, string strSord)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            //jsonBuilder.Append("\"");rows=10&page=2&sidx=&sord=asc   where (int)r[""] == 2
            //jsonBuilder.Append("{\"page\":" + iCurrPageNum.ToString() + ",\"total\":" + System.Math.Ceiling(((double)(dt.Rows.Count) / (double)iPageRows)).ToString() + ",\"records\":" + dt.Rows.Count + ",\"rows\"");
            //jsonBuilder.Append(":[");

            jsonBuilder.Append("{\"rows\":[");
            //只返回当前页数据
            if (strSortFieldNme != string.Empty && strSord != string.Empty && dt.Columns.IndexOf(strSortFieldNme) != -1)
                dt.DefaultView.Sort = strSortFieldNme + " " + strSord;
            LinqList<DataRowView> lqrows = new LinqList<DataRowView>(dt.DefaultView);
            IEnumerable<DataRowView> selectedRows = (from r in lqrows select r).Take(iRCount);
            //IEnumerable<DataRowView> selectedRows = (from r in lqrows where (string)r[0] == (string)r[0] select r).Take(iRCount);
            int k = 0;
            foreach (DataRowView row in selectedRows)
            {
                string strKey = row[0].ToString();
                //if (strKeyFieldNme != string.Empty && dt.Columns.IndexOf(strKeyFieldNme) != -1)
                //    strKey = row[strKeyFieldNme].ToString();
                if (k != 0)
                    jsonBuilder.Append(",");
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":");
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(HttpTools.stringToJson(row[dt.Columns[j].ColumnName].ToString()));
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("}");
                k++;
            }
            //jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        //[{"order_no":1031,"employee":"RA","country":"Ed","customer":"Sidney","order2005":61,"order2006":31,"order2007":80,"order2008":47,"delivery_date":"2008-10-16"},{"order_no":1032,"employee":"CA","country":"Pa","customer":"Solomon","order2005":82,"order2006":70,"order2007":33,"order2008":38,"delivery_date":"2008-4-21"},{"order_no":1033,"employee":"MA","country":"Le","customer":"Glendon","order2005":90,"order2006":77,"order2007":98,"order2008":36,"delivery_date":"2008-8-7"},{"order_no":1034,"employee":"SP","country":"Te","customer":"Edwin","order2005":64,"order2006":47,"order2007":84,"order2008":41,"delivery_date":"2008-10-4"},{"order_no":1035,"employee":"SP","country":"Br","customer":"Mike","order2005":35,"order2006":73,"order2007":97,"order2008":83,"delivery_date":"2008-3-2"},{"order_no":1036,"employee":"MA","country":"ww","customer":"22","order2005":50,"order2006":57,"order2007":80,"order2008":46,"delivery_date":"2008-10-22"},{"order_no":1037,"employee":"CA","country":"Ev","customer":"Chris","order2005":66,"order2006":76,"order2007":43,"order2008":63,"delivery_date":"2008-4-4"},{"order_no":1038,"employee":"IN","country":"Ro","customer":"Samuel","order2005":63,"order2006":49,"order2007":85,"order2008":68,"delivery_date":"2008-7-11"},{"order_no":1039,"employee":"MA","country":"Gl","customer":"Oscar","order2005":94,"order2006":96,"order2007":62,"order2008":33,"delivery_date":"2008-11-16"},{"order_no":1040,"employee":"MA","country":"Co","customer":"Peter","order2005":76,"order2006":86,"order2007":77,"order2008":67,"delivery_date":"2008-12-12"},{"order_no":1041,"employee":"YY","country":"Ja","customer":"Benson","order2005":88,"order2006":96,"order2007":56,"order2008":33,"delivery_date":"2008-11-16"},{"order_no":1044,"employee":"CA","country":"Se","customer":"Hunk","order2005":50,"order2006":45,"order2007":46,"order2008":72,"delivery_date":"2008-9-18"},{"order_no":1045,"employee":"IN","country":"Ke","customer":"Bob","order2005":62,"order2006":64,"order2007":61,"order2008":61,"delivery_date":"2008-1-19"},{"order_no":1046,"employee":"US","country":"Ja","customer":"Coli","order2005":72,"order2006":92,"order2007":56,"order2008":41,"delivery_date":"2008-11-20"},{"order_no":1047,"employee":"IN","country":"Br","customer":"Ivan","order2005":68,"order2006":62,"order2007":66,"order2008":78,"delivery_date":"2008-2-13"},{"order_no":1048,"employee":"SP","country":"Sa","customer":"Vern","order2005":93,"order2006":66,"order2007":85,"order2008":71,"delivery_date":"2008-12-18"},{"order_no":1049,"employee":"US","country":"Br","customer":"Leopold","order2005":45,"order2006":70,"order2007":52,"order2008":39,"delivery_date":"2008-11-7"},{"order_no":1050,"employee":"CA","country":"Le","customer":"Caspar","order2005":62,"order2006":94,"order2007":53,"order2008":88,"delivery_date":"2008-3-18"},{"order_no":1051,"employee":"SP","country":"Ju","customer":"Joe","order2005":38,"order2006":97,"order2007":35,"order2008":74,"delivery_date":"2008-7-31"},{"order_no":1052,"employee":"UK","country":"Co","customer":"Thomas","order2005":55,"order2006":58,"order2007":62,"order2008":46,"delivery_date":"2008-7-19"},{"order_no":1053,"employee":"MA","country":"Gi","customer":"Andrew","order2005":33,"order2006":52,"order2007":68,"order2008":67,"delivery_date":"2008-11-11"},{"order_no":1054,"employee":"SP","country":"Br","customer":"Gary","order2005":61,"order2006":54,"order2007":62,"order2008":42,"delivery_date":"2008-8-16"},{"order_no":1055,"employee":"RA","country":"Ry","customer":"Bob","order2005":83,"order2006":50,"order2007":34,"order2008":46,"delivery_date":"2008-12-1"},{"order_no":1056,"employee":"US","country":"Ga","customer":"Johnny","order2005":45,"order2006":56,"order2007":36,"order2008":79,"delivery_date":"2008-2-23"},{"order_no":1057,"employee":"CA","country":"Ra","customer":"Carl","order2005":59,"order2006":42,"order2007":65,"order2008":47,"delivery_date":"2008-9-20"},{"order_no":1058,"employee":"MA","country":"Je","customer":"Keith","order2005":50,"order2006":57,"order2007":80,"order2008":46,"delivery_date":"2008-10-2"},{"order_no":1061,"employee":"WW","country":"BT","customer":"Mdidi","order2005":444,"order2006":444,"order2007":0,"order2008":0,"delivery_date":"2008-1-1"},{"order_no":1062,"employee":"qqq","country":"qq","customer":"qq","order2005":0,"order2006":0,"order2007":0,"order2008":0,"delivery_date":"2008-1-1"},{"order_no":1064,"employee":"www","country":"df","customer":"www","order2005":12,"order2006":12,"order2007":12,"order2008":0,"delivery_date":"2008-1-1"}] 


        public static string GetJsonForgtGrid(DataTable dt, msBsc.AppLogic.Cfg.gtGridCRecord gtGridRet, string strREJson,string strSaveJson="")
        {
            StringBuilder sbJson = new StringBuilder();
            sbJson.Append("[");
            //string data = "";
            //data += "[";

            if (dt != null)
            {
                //只返回当前页数据 
                string strFilter = "";
                for (int i = 0; i < gtGridRet.filterInfo.Length; i++)
                {
                    string strLogic = "";
                    if (gtGridRet.filterInfo[i].Logic == "equal")
                        strLogic = "=" + "'" + gtGridRet.filterInfo[i].value + "'";
                    else if (gtGridRet.filterInfo[i].Logic == "notEqual")
                        strLogic = "<>" + "'" + gtGridRet.filterInfo[i].value + "'";
                    else if (gtGridRet.filterInfo[i].Logic == "less")
                        strLogic = "<" + "'" + gtGridRet.filterInfo[i].value + "'";
                    else if (gtGridRet.filterInfo[i].Logic == "great")
                        strLogic = ">" + "'" + gtGridRet.filterInfo[i].value + "'";
                    else if (gtGridRet.filterInfo[i].Logic == "lessEqual")
                        strLogic = "<=" + "'" + gtGridRet.filterInfo[i].value + "'";
                    else if (gtGridRet.filterInfo[i].Logic == "greatEqual")
                        strLogic = ">=" + "'" + gtGridRet.filterInfo[i].value + "'";
                    else if (gtGridRet.filterInfo[i].Logic == "like")
                        strLogic = " like " + "'%" + gtGridRet.filterInfo[i].value + "%'";
                    else if (gtGridRet.filterInfo[i].Logic == "startWith")
                        strLogic = " like " + "'" + gtGridRet.filterInfo[i].value + "%'";
                    else if (gtGridRet.filterInfo[i].Logic == "endWith")
                        strLogic = " like " + "'%" + gtGridRet.filterInfo[i].value + "'";
                    if (strLogic == "")
                        continue;
                    string strftem = "(" + gtGridRet.filterInfo[i].FieldName + " " + strLogic + ")";
                    strFilter += strFilter == "" ? strftem : " and " + strftem;
                }
                dt.DefaultView.RowFilter = strFilter;

                string strSort = "";
                for (int i = 0; i < gtGridRet.sortInfo.Length; i++)
                {
                    strSort += strSort == "" ? gtGridRet.sortInfo[i].ColumnId + " " + gtGridRet.sortInfo[i].sortOrder : "," + gtGridRet.sortInfo[i].ColumnId + " " + gtGridRet.sortInfo[i].sortOrder;
                }
                dt.DefaultView.Sort = strSort;
                //DataTable dtRettem= dt.DefaultView.ToTable();
                //DataRow[] arrrowret= dtRettem.Select("");
                int istartrow = (gtGridRet.pageInfo.PageNum - 1) * gtGridRet.pageInfo.PageSize;


                msBsc.AppLogic.Cfg.SynDictionary htColumns = new msBsc.AppLogic.Cfg.SynDictionary(false);
                for (int i = 0; i < gtGridRet.columnInfo.Length; i++)
                {
                    if (dt.Columns.IndexOf(gtGridRet.columnInfo[i].Id) == -1)
                    {
                        dt.Columns.Add(new DataColumn(gtGridRet.columnInfo[i].Id, System.Type.GetType("System.String")));
                    }
                }
                for (int i = istartrow; i < dt.DefaultView.Count && i < istartrow + gtGridRet.pageInfo.PageSize; i++)
                {
                    DataRow row = dt.DefaultView[i].Row;
                    if (i > istartrow)
                        sbJson.Append(",");
                    sbJson.Append("{");
                    for (int j = 0; j < gtGridRet.columnInfo.Length; j++)
                    {
                        if (j > 0)
                            sbJson.Append(",");
                        if (gtGridRet.columnInfo[j].Id != string.Empty)
                        {
                            sbJson.Append("\"" + gtGridRet.columnInfo[j].Id + "\"");
                            sbJson.Append(":\"" + HttpTools.stringToJson(row[gtGridRet.columnInfo[j].Id].ToString()) + "\"");
                        }
                    }
                    sbJson.Append("}");
                    //k++;
                }




                //LinqList<DataRowView> lqrows = new LinqList<DataRowView>(dt.DefaultView);
                //IEnumerable<DataRowView> selectedRows = (from r in lqrows select r).Skip((gtGridRet.pageInfo.PageNum - 1) * gtGridRet.pageInfo.PageSize).Take(gtGridRet.pageInfo.PageSize);
                //int k = 0;
                //foreach (DataRowView row in selectedRows)
                //{
                //    if (k > 0)
                //        data += ",";
                //    data += "{";
                //    for (int j = 0; j < gtGridRet.columnInfo.Length; j++)
                //    {
                //        if (j > 0)
                //            data += ",";
                //        if (gtGridRet.columnInfo[j].Id != string.Empty)
                //        {
                //            if (dt.Columns.IndexOf(gtGridRet.columnInfo[j].Id) != -1)
                //            {
                //                data += "\"" + gtGridRet.columnInfo[j].Id + "\"";
                //                data += ":\"" + HttpTools.stringToJson(row[gtGridRet.columnInfo[j].Id].ToString()) + "\"";
                //            }
                //            else
                //            {
                //                dt.Columns.Add(new DataColumn(gtGridRet.columnInfo[j].Id, System.Type.GetType("System.String")));
                //                data += "\"" + gtGridRet.columnInfo[j].Id + "\"";
                //                data += ":\"\"";
                //            }
                //        }
                //    }
                //    data += "}";


                //    k++;
                //}
                gtGridRet.pageInfo.TotalRowNum = dt.DefaultView.Count;
            }
            sbJson.Append("]");

            string ret = "{data:" + sbJson.ToString() + ",\n";
            if (strSaveJson != string.Empty)
            {
                ret += strSaveJson + ",\n";
            }
            if (strREJson != string.Empty)
            {
                ret += "recordType : 'object'" + ",\n"
                    + gtGridRet.PageInfoJsonString + ",\n"
                    + strREJson + "}";
            }
            else
            {
                ret += "recordType : 'object'" + ",\n"
                    + gtGridRet.PageInfoJsonString + " }";
            }
            return ret;
        }

        /// <summary>
        /// 获取记录的JSON编码
        /// </summary>
        /// <param name="drw"></param>
        /// <returns></returns>
        public static string DataRowToJson(DataRow drw)
        {
            if (drw == null)
            {
                return "";
            }
            StringBuilder sbJson = new StringBuilder();

            sbJson.Append("{");
            for (int c = 0; c < drw.Table.Columns.Count; c++)
            {
                if (c > 0)
                {
                    sbJson.Append(",");
                }
                sbJson.Append(drw.Table.Columns[c].ToString() + ":\"" + HttpTools.stringToJson(drw[c].ToString()) + "\"");
            }
            sbJson.Append("}");
            return sbJson.ToString();
        }

        /// <summary>  
        /// 根据DataTable返回JSON数据格式如:  
        /// {table:[{column1:1,column2:2,column3:3},{column1:1,column2:2,column3:3}]}  
        /// </summary>  
        /// <param name="tb">需要转换的表</param>  
        /// <returns></returns>  
        public static string DateTableToJson(DataTable tb)
        {
            if (tb == null || tb.Rows.Count == 0)
            {
                return "";
            }

            string strName = "table";
            /* 
            string strName = tb.TableName; 
            if (strName.Trim().Length == 0) 
            { 
                strName = "table"; 
            }*/
            StringBuilder sbJson = new StringBuilder();
            sbJson.Append("{");
            sbJson.Append("\"" + strName + "\":[");
            msBsc.AppLogic.Cfg.SynDictionary htColumns = new msBsc.AppLogic.Cfg.SynDictionary(false);
            for (int i = 0; i < tb.Columns.Count; i++)
            {
                htColumns.Add(i.ToString(), tb.Columns[i].ColumnName.Trim());
            }

            for (int j = 0; j < tb.Rows.Count; j++)
            {
                if (j != 0)
                {
                    sbJson.Append(",");
                }
                sbJson.Append("{");
                for (int c = 0; c < tb.Columns.Count; c++)
                {
                    sbJson.Append(htColumns[c.ToString()].ToString() + ":\"" + HttpTools.stringToJson(tb.Rows[j][c].ToString()) + "\",");
                }
                sbJson.Append("index:" + j.ToString()); //序号  
                sbJson.Append("}");
            }
            sbJson.Append("]}");
            return sbJson.ToString();
        }










        //"pageInfo\":{\"pageSize\":20,\"pageNum\":1,\"totalRowNum\":-1,\"totalPageNum\":1,\"startRowNum\":1,\"endRowNum\":20},

        public static void CopyHashToDataRow(msBsc.AppLogic.Cfg.SynDictionary srcHash, DataRow drw, string strNotCopyCols = "")
        {
            if (!string.IsNullOrEmpty(strNotCopyCols))
            {
                strNotCopyCols = "," + strNotCopyCols + ",";
            }
            string[] arrKey = srcHash.Keys;// new string[srcHash.Keys.Count];
            //srcHash.Keys.CopyTo(arrKey, 0);
            for (int i = 0; i < arrKey.Length; i++)
            {
                string strColum = arrKey[i];
                if (!string.IsNullOrEmpty(strNotCopyCols) && strNotCopyCols.IndexOf(strColum) != -1)
                {
                    continue;
                }
                if (drw.Table.Columns.IndexOf(strColum) == -1)
                    continue;
                if (drw.Table.Columns[strColum].DataType == typeof(global::System.TimeSpan)
                    && (srcHash[arrKey[i]] == null ? string.Empty : srcHash[arrKey[i]].ToString()) != drw[strColum].ToString())
                {
                    if (srcHash[arrKey[i]] == null || srcHash[arrKey[i]].ToString() == string.Empty)
                        drw[strColum] = DBNull.Value;
                    else
                        drw[strColum] = TimeSpan.Parse(srcHash[arrKey[i]].ToString());
                }
                else if (drw.Table.Columns[strColum].DataType == typeof(global::System.DateTime)
                    && (srcHash[arrKey[i]] == null ? string.Empty : srcHash[arrKey[i]].ToString()) != drw[strColum].ToString())
                {
                    if (srcHash[arrKey[i]] == null || srcHash[arrKey[i]].ToString() == string.Empty)
                        drw[strColum] = DBNull.Value;
                    else
                        drw[strColum] = DateTime.Parse(srcHash[arrKey[i]].ToString());
                }
                else if (drw.Table.Columns[strColum].DataType == typeof(decimal)
                    && decimal.Parse(srcHash[arrKey[i]] == null || srcHash[arrKey[i]].ToString() == string.Empty ? "0" : srcHash[arrKey[i]].ToString())
                    != decimal.Parse(drw[strColum].ToString() == string.Empty ? "0" : drw[strColum].ToString()))
                {
                    if (srcHash[arrKey[i]] == null || srcHash[arrKey[i]].ToString() == string.Empty)
                        drw[strColum] = 0;
                    else
                        drw[strColum] = decimal.Parse(srcHash[arrKey[i]].ToString());
                }
                else if (drw.Table.Columns[strColum].DataType == typeof(int)
                    && int.Parse(srcHash[arrKey[i]] == null || srcHash[arrKey[i]].ToString() == string.Empty ? "0" : srcHash[arrKey[i]].ToString())
                    != int.Parse(drw[strColum].ToString() == string.Empty ? "0" : drw[strColum].ToString()))
                {
                    if (srcHash[arrKey[i]] == null || srcHash[arrKey[i]].ToString() == string.Empty)
                    {
                        drw[strColum] = 0;
                    }
                    else if (srcHash[arrKey[i]].ToString().IndexOf(".") != -1)
                    {
                        drw[strColum] = Convert.ToInt32(Convert.ToDecimal(srcHash[arrKey[i]].ToString()));
                    }
                    else
                    {
                        drw[strColum] = Convert.ToInt32(srcHash[arrKey[i]].ToString());
                    }
                }
                else if (drw.Table.Columns[strColum].DataType == typeof(Int16)
                    && Int16.Parse(srcHash[arrKey[i]] == null || srcHash[arrKey[i]].ToString() == string.Empty ? "0" : srcHash[arrKey[i]].ToString())
                    != Int16.Parse(drw[strColum].ToString() == string.Empty ? "0" : drw[strColum].ToString()))
                {
                    if (srcHash[arrKey[i]] == null || srcHash[arrKey[i]].ToString() == string.Empty)
                    {
                        drw[strColum] = 0;
                    }
                    else if (srcHash[arrKey[i]].ToString().IndexOf(".") != -1)
                    {
                        drw[strColum] = Convert.ToInt16(Convert.ToDecimal(srcHash[arrKey[i]].ToString()));
                    }
                    else
                    {
                        drw[strColum] = Convert.ToInt16(srcHash[arrKey[i]].ToString());
                    }
                }
                //else if (drw.Table.Columns[strColum].DataType == typeof(global::System.Byte)
                //    && Byte.Parse(srcHash[arrKey[i]] == null || srcHash[arrKey[i]].ToString() == string.Empty ? "0" : srcHash[arrKey[i]].ToString())
                //    != Byte.Parse(drw[strColum].ToString() == string.Empty ? "0" : drw[strColum].ToString()))
                //{
                //    if (srcHash[arrKey[i]] == null || srcHash[arrKey[i]].ToString() == string.Empty)
                //        drw[strColum] = 0;
                //    else
                //        drw[strColum] = Byte.Parse(srcHash[arrKey[i]].ToString());
                //}
                else if (drw.Table.Columns[strColum].DataType == typeof(bool)
                    && (srcHash[arrKey[i]] == null ? string.Empty : srcHash[arrKey[i]].ToString()) != drw[strColum].ToString())
                {
                    if (srcHash[arrKey[i]] == null || srcHash[arrKey[i]].ToString() == string.Empty)
                        drw[strColum] = false;
                    else
                        drw[strColum] = (srcHash[arrKey[i]].ToString()).ToLower() == "true" || (srcHash[arrKey[i]].ToString()).ToLower() == "1";
                }
                else if ((srcHash[arrKey[i]] == null ? string.Empty : srcHash[arrKey[i]].ToString()) != drw[strColum].ToString())
                {
                    if (srcHash[arrKey[i]] == null || srcHash[arrKey[i]].ToString() == string.Empty)
                        drw[strColum] = "";
                    else
                        drw[strColum] = srcHash[arrKey[i]].ToString();
                }
            }
        }

        public static void gtExport(DataTable dt, msBsc.AppLogic.Cfg.gtGridCRecord gtGridRet)
        {
            if (gtGridRet.exportType == "xls")
            {
                int r = 0;
                for (int i = 0; i < gtGridRet.columnInfo.Length; i++)
                {
                    int item1 = dt.Columns.IndexOf(gtGridRet.columnInfo[i].Id);
                    if (gtGridRet.columnInfo[i].Exportable.ToUpper() == "TRUE" && item1 != -1)
                    {
                        r++;
                    }
                }
                string[] arriHead = new string[r];
                int[] arriCol = new int[r]; r = 0;
                for (int i = 0; i < gtGridRet.columnInfo.Length; i++)
                {
                    int item1 = dt.Columns.IndexOf(gtGridRet.columnInfo[i].Id);
                    if (gtGridRet.columnInfo[i].Exportable.ToUpper() == "TRUE" && item1 != -1)
                    {
                        arriCol[r] = item1;
                        arriHead[r] = gtGridRet.columnInfo[i].Header;
                        r++;
                    }
                }
                //string fileName = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + gtGridRet.exportFileName + "." + gtGridRet.exportType;
                //Export oExport = new Export();
                //oExport.ExportDetails(dt, arriCol, arriHead, Export.ExportFormat.Excel, fileName);



                //if (File.Exists(fileName))
                //{
                //    HttpContext.Current.Response.AppendHeader("Content-Type", "application/octet-stream");
                //    HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + HttpContext.Current.Server.UrlEncode(Path.GetFileName(fileName)));
                //    HttpContext.Current.Response.WriteFile(fileName, false);
                //}



                //if (dt == null)
                //{
                //    return;
                //}
                //DateTime gBeforeProcessStartTime, gAfterProcessStartTime;
                //gBeforeProcessStartTime = System.DateTime.Now.AddSeconds(-1);
                //Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();
                //gAfterProcessStartTime = System.DateTime.Now.AddSeconds(1);
                //xlsApp.Visible = false;
                //try
                //{
                //    if (xlsApp == null)
                //    {
                //        HttpContext.Current.Response.Write("<script>alert('无法创建Excel对象，可能您的机子未安装Excel')</script>");
                //        return;
                //    }

                //    Microsoft.Office.Interop.Excel.Workbook wbook = xlsApp.Workbooks.Add(true); ;
                //    Microsoft.Office.Interop.Excel.Worksheet wsheet = (Microsoft.Office.Interop.Excel.Worksheet)wbook.Worksheets[1];
                //    Microsoft.Office.Interop.Excel.Range range = null;

                //    xlsApp.Application.DisplayAlerts = false;

                //    for (int i = 0; i < gtGridRet.columnInfo.Length; i++)
                //    {
                //        if (gtGridRet.columnInfo[i].Exportable.ToUpper() == "TRUE" && dt.Columns.IndexOf(gtGridRet.columnInfo[i].Id) != -1)
                //        {

                //            wsheet.Cells[1, i] = gtGridRet.columnInfo[i].Header;
                //            range = (Microsoft.Office.Interop.Excel.Range)wsheet.Cells[1, i];
                //            range.Interior.ColorIndex = 20;
                //            range.Font.Bold = true;
                //        }
                //    }
                //    for (int j = 0; j < dt.Rows.Count; j++)
                //    {
                //        for (int a = 0; a < gtGridRet.columnInfo.Length; a++)
                //        {
                //            if (gtGridRet.columnInfo[a].Exportable.ToUpper() == "TRUE" && dt.Columns.IndexOf(gtGridRet.columnInfo[a].Id) != -1)
                //            {
                //                wsheet.Cells[j + 2, a] = dt.Rows[j][gtGridRet.columnInfo[a].Id];
                //            }
                //        }
                //    }
                //    range = wsheet.get_Range(wsheet.Cells[2, 1], wsheet.Cells[dt.Rows.Count + 1, gtGridRet.columnInfo.Length]);
                //    range.EntireColumn.AutoFit();
                //    range.EntireRow.AutoFit();
                //    range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                //    range.VerticalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                //    wbook.Saved = true;

                //    string fileName = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + gtGridRet.exportFileName + "." + gtGridRet.exportType;
                //    if (!File.Exists(fileName))
                //    {
                //        File.Create(fileName);
                //    }
                //    wbook.SaveCopyAs(fileName);
                //    System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
                //    range = null;
                //    System.Runtime.InteropServices.Marshal.ReleaseComObject(wsheet);
                //    wsheet = null;
                //    System.Runtime.InteropServices.Marshal.ReleaseComObject(wbook);
                //    wbook = null;
                //    xlsApp.Quit();
                //    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlsApp);
                //    xlsApp = null;
                //    GC.Collect();
                //    SysProcessm.Kill("excel", gBeforeProcessStartTime, gAfterProcessStartTime);

                //    if (File.Exists(fileName))
                //    {
                //        HttpContext.Current.Response.AppendHeader("Content-Type", "application/octet-stream");
                //        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + HttpContext.Current.Server.UrlEncode(Path.GetFileName(fileName)));
                //        HttpContext.Current.Response.WriteFile(fileName, false);
                //    }
                //}
                //catch
                //{
                //    SysProcessm.Kill("excel", gBeforeProcessStartTime, gAfterProcessStartTime);
                //}
            }
            else if (gtGridRet.exportType == "pdf")
            {

            }
        }
    }

}

